package com.csxy.six.config;

import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SwaggerResourceConfig {

    private final RouteDefinitionLocator routeLocator;

    public SwaggerResourceConfig(RouteDefinitionLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Bean
    public List<GroupedOpenApi> apis() {
        List<GroupedOpenApi> groups = new ArrayList<>();
        List<String> routes = new ArrayList<>();

        // 从路由定义中获取所有服务ID
        routeLocator.getRouteDefinitions().collectList().block().forEach(route -> {
            String serviceId = route.getId();
            if (serviceId != null && (serviceId.startsWith("service-") || serviceId.startsWith("material-"))) {
                routes.add(serviceId);
            }
        });

        // 为每个服务创建分组
        routes.forEach(service -> {
            String groupName = service.replace("-service", "");
            groups.add(GroupedOpenApi.builder()
                    .pathsToMatch("/" + groupName + "/**")
                    .group(groupName)
                    .build());
        });

        return groups;
    }
}